import Cookies from 'js-cookie'
import $ from 'jquery'

/**
 * @desc 获取egg注入的cookie-token
 */
export function getEggCookieToken() {
  const EGG_COOKIE_TOKEN_KEY = 'csrfToken'
  const token = Cookies.get(EGG_COOKIE_TOKEN_KEY)

  return token
}

/**
 * @dsec 等待时间
 * @param {number?} ms 毫秒
 */
export async function waiting(ms = 1000) {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve()
    }, ms)
  })
}

/**
 * @desc 绑定滚动到底部的监听(JQuery)
 * @param {function?} callback 滚动到底部时触发
 * @param {object?} options 选项
 * @param {function?} options.getElement 指定元素,默认为window
 * @param {number?} options.offset 触发偏移
 * @param {number?} options.delay 防抖延迟(ms)
 *
 * @returns {function} cancelHandle 用于取消滚动监听
 */
export function bindReachBottom(callback = () => {}, { getElement = () => window, offset = 50, delay = 200 } = {}) {
  const el = getElement()
  let timer = null

  // 绑定函数
  function handleBottom() {
    timer && clearTimeout(timer)
    timer = setTimeout(() => {
      const viewHeight = $(el).height()
      const contentHeight =
        $(el)[0].scrollHeight || window.document.body.scrollHeight || window.document.documentElement.scrollHeight
      const scrollTop = $(el).scrollTop()

      if (viewHeight + scrollTop >= contentHeight - offset) {
        callback && callback({ viewHeight, contentHeight, scrollTop })
      }
    }, delay)
  }

  $(el).on('scroll', handleBottom)

  // 最后返回一个解绑函数
  function cancelHandle() {
    $(el).off('scroll', handleBottom)
  }

  return cancelHandle
}

/**
 * @desc hsla 转为 rgba
 * @param {Number} h 色相 [0-360]
 * @param {Number} s 饱和度 [0-1]
 * @param {Number} l 亮度 [0-1] 0.5时为正常
 * @param {Number} a 透明度 [0-1]
 */
export function hsla2rgba(h = 0, s = 1, l = 0.5, a = 1) {
  let r, g, b
  let deg = h % 360
  // 将色相转化为[0-1]的数值
  deg = deg < 0 ? 360 + deg : deg
  const num = Math.floor((1000 * deg) / 360) / 1000

  if (s === 0) {
    r = g = b = l
  } else {
    const hue2rgb = (p, q, t) => {
      if (t < 0) t += 1
      if (t > 1) t -= 1
      if (t < 1 / 6) return p + (q - p) * 6 * t
      if (t < 1 / 2) return q
      if (t < 2 / 3) return p + (q - p) * (2 / 3 - t) * 6
      return p
    }

    const q = l < 0.5 ? l * (1 + s) : l + s - l * s
    const p = 2 * l - q
    r = hue2rgb(p, q, num + 1 / 3)
    g = hue2rgb(p, q, num)
    b = hue2rgb(p, q, num - 1 / 3)
  }

  return `rgba(${Math.floor(r * 255)},${Math.floor(g * 255)},${Math.floor(b * 255)},${a})`
}
